<template>
  <v-card outlined>
    <v-card-title>
      评估结果摘要
      <v-spacer></v-spacer>
      <v-btn
          color="success"
          @click="generateSelectedReports"
          :disabled="selectedItems.length === 0 || isLoading"
          :loading="isLoading"
          class="ml-4"
      >
        生成选中报告 ({{ selectedItems.length }})
      </v-btn>
    </v-card-title>
    <v-card-text>
      <v-progress-linear
          v-if="isLoading || progress > 0 && progress < 100"
          :model-value="progress"
          color="primary"
          height="10"
          striped
          class="mb-2"
      ></v-progress-linear>
      <v-data-table
          v-model="selectedItems"
          :headers="headers"
          :items="tableItems"
          item-value="id"
          show-select
          class="elevation-1"
          :loading="isLoading"
          loading-text="正在加载评估结果..."
          no-data-text="请先上传并评估设备数据"
      >
        <template v-slot:item.evaluation.grade="{ item }">
          <v-chip :color="getGradeColor(item?.raw?.evaluation?.grade || (item?.raw?.error ? '错误' : 'N/A'))" dark small>
            {{ item?.raw?.evaluation?.grade || (item?.raw?.error ? '错误' : 'N/A') }}
          </v-chip>
        </template>
        <template v-slot:item.evaluation.finalRealPrice="{ item }">
          {{ item?.raw?.evaluation?.finalRealPrice ? formatPrice(item.raw.evaluation.finalRealPrice) : '-' }}
        </template>
        <template v-slot:item.actions="{ item }">
          <v-btn icon variant="text" color="primary" @click="viewDetails(item?.raw)" title="查看详情" :disabled="!item?.raw?.evaluation">
            <img src="@/assets/icons/detail.svg" alt="查看详细" style="width: 20px; height: 20px;" />
          </v-btn>
          <v-btn icon="mdi-file-pdf-box" variant="text" color="red" @click="generateSingleReport(item?.raw)" :disabled="!item?.raw?.evaluation || item?.raw?.error" title="生成单个报告">
            <img src="@/assets/icons/pdf.svg" alt="导出pdf" style="width: 20px; height: 20px;" />

          </v-btn>
        </template>
        <template v-slot:item.error="{ item }">
          <v-tooltip location="top" v-if="item?.raw?.error">
            <template v-slot:activator="{ props }">
              <v-icon color="error" v-bind="props">mdi-alert-circle</v-icon>
            </template>
            <span>{{ item.raw.error }}</span>
          </v-tooltip>
        </template>
      </v-data-table>
    </v-card-text>
  </v-card>
</template>

<script setup>
import { ref, computed, watch } from 'vue';

const props = defineProps({
  results: {
    type: Array,
    required: true,
    default: () => [],
    validator: (value) => {
      return value.every(item => {
        if (!item.id || !item.name || !item.model) return false;
        if (item.evaluation !== undefined && item.evaluation !== null && typeof item.evaluation !== 'object') return false;
        return !(item.error !== undefined && typeof item.error !== 'string');

      });
    }
  },
  isLoading: {
    type: Boolean,
    default: false
  },
  progress: {
    type: Number,
    default: 0
  }
});

const emit = defineEmits(['view-details', 'generate-reports', 'generate-single-report']);

const selectedItems = ref([]); // 存储选中项目的 'id'

const tableItems = computed(() => {
  return props.results.map(item => ({
    ...item,
    raw: item // 确保 raw 是原始对象
  }));
});

const headers = ref([
  {title: '设备名称', key: 'name', sortable: true},
  {title: '设备型号', key: 'model', sortable: true},
  {title: '评估等级', key: 'evaluation.grade', sortable: true, align: 'center'},
  {title: '评估价值 (元)', key: 'evaluation.finalRealPrice', sortable: true, align: 'end'},
  {title: '错误', key: 'error', sortable: false, align: 'center'},
  {title: '操作', key: 'actions', sortable: false, align: 'center'},
]);

const gradeColors = {
  'A': 'green', 'B': 'green', 'C': 'orange', 'D': 'orange', 'E': 'red', 'F': 'red', '建议报废': 'black',
};

function getGradeColor(grade) {
  if (grade === '错误') return 'red';
  return gradeColors[grade] || 'grey';
}

function formatPrice(price) {
  if (price === null || price === undefined || isNaN(price)) {
    return '-';
  }
  return parseFloat(price).toFixed(2);
}

function viewDetails(item) {
  if (item) {
    emit('view-details', item);
  }
}

function generateSelectedReports() {
  const itemsToReport = props.results.filter(r => selectedItems.value.includes(r.id));
  emit('generate-reports', itemsToReport);
}

function generateSingleReport(item) {
  if (item) {
    emit('generate-single-report', item);
  }
}

watch(() => props.results, (newResults) => {
  console.log('EvaluationResultsSummary 中的 Results:', newResults);
  newResults.forEach((item, index) => {
    console.log(`Result 项 ${index}:`, item);
  });
});
</script>

<style scoped>
/* 如果需要，为摘要表格添加特定样式 */
</style>